/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fr.fleroy.gedappservices.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;

/**
 *
 * @author Fabrice
 */
public class WebDavUtil {

    private HttpClient moClient =null;

    public WebDavUtil(){
        HostConfiguration hostConfig = new HostConfiguration();
        hostConfig.setHost("192.168.1.3", 5005);
        HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
        HttpConnectionManagerParams params = new HttpConnectionManagerParams();
        int maxHostConnections = 20;
        params.setMaxConnectionsPerHost(hostConfig, maxHostConnections);
        connectionManager.setParams(params);
        moClient = new HttpClient(connectionManager);
        Credentials creds = new UsernamePasswordCredentials("Fabrice", "petitewowot83");
        moClient.getState().setCredentials(AuthScope.ANY, creds);
        moClient.setHostConfiguration(hostConfig);
    }

    public HttpClient getClient() {
        return moClient;
    }

    public boolean upload(File poFile){
        try {
            PutMethod loPut = new PutMethod(moClient.getHostConfiguration().getHostURL() + "/Private_Fab/GED/" + poFile.getName());
            RequestEntity requestEntity = new InputStreamRequestEntity(new FileInputStream(poFile));
            loPut.setRequestEntity(requestEntity);
            moClient.executeMethod(loPut);
            System.out.println(loPut.getStatusCode() + " " + loPut.getStatusText());
            loPut.releaseConnection();
        } catch (IOException ex) {
            Logger.getLogger(WebDavUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;
    }

}
